package com.yupi.springbootinit.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * EasyExcel 测试
 *
 *
 */
@Component
public class ExcelUtils {

    public static String excelToCsv(MultipartFile multipartFile) {
        // easyexcel 分析
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 保存打印
        StringBuilder result = new StringBuilder();
        // 头表
        LinkedHashMap<Integer, String> headerDate = (LinkedHashMap) list.get(0);
        List<String> headerList = headerDate.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
        result.append(StringUtils.join(headerList, ",")).append("\n");

        // 数据
        for(int i = 1; i < list.size(); i++){
            LinkedHashMap<Integer, String> detailDate = (LinkedHashMap) list.get(i);
            List<String> detailList = detailDate.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
            result.append(StringUtils.join(detailList, ",")).append("\n");
        }

        return result.toString();
    }
}